﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web.Mvc;
using BSF.Enums;
using BSF.SystemConfig;
using Bzw.Data;
using HuntingFishGame.ManageDomain.BLL.User;
using HuntingFishGame.ManageDomain.BLL.WeChat;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace HuntingFishGame.H5.Controllers
{
    public class UserCheckInController : Controller
    {
        #region 申明
        public string wxUserID = "";
        public string username = "";
        public string userpwd = "";
        public string mony = "";
        #endregion

        // GET: UserCheckIn
        public ActionResult Index()
        {
            string code = Request.Params["code"];//页面已授权，可以得到code。
            if (!string.IsNullOrEmpty(code))
                GetOpid(code);
            if (Session["wxUserID"] != null && Session["wxUserID"].ToString() != "")
            {
                wxUserID = wxUserID == "" ? Session["wxUserID"].ToString() : wxUserID;
                string logContent = "SessionID的值为：" + Session["wxUserID"].ToString() + ",时间为：" + DateTime.Now;
                Helper.ExtLog(logContent);
            }
            int count = 0;
            var userList = WxCodeBLL.GetList(BSFConfig.GameConnectString, wxUserID, 1, 20, out count);
            return View(userList);
        }

        #region 获取微信用户ID
        /// <summary>
        /// 获取微信用户ID
        /// </summary>
        public void GetOpid(string code)
        {
            string logContent = "";
            string appid = Helper.GetConfig("appid");
            string secret = Helper.GetConfig("secret");
            //获取网页授权access_token（调用次数限制:无）。这里通过code换取的是一个特殊的网页授权access_token,与基础支持中的access_token（该access_token用于调用其他接口）不同
            //OAuthAccessTokenResult userToken = WeChatUrlBLL.GetUserAccessToken(WeixinConfig.AppId(WeixinType.CertServiceAccount), WeixinConfig.AppSecret(WeixinType.CertServiceAccount), code);
            OAuthAccessTokenResult userToken = WeChatUrlBLL.GetUserAccessToken(appid, secret, code);
            if (userToken != null && userToken.CheckIsSuccess())
            {
                wxUserID = userToken.openid;//微信用户ID存入全局变量
                Session["wxUserID"] = userToken.openid;//微信用户ID存入session会话
                logContent = "获取微信返回信息：" + JsonConvert.SerializeObject(userToken) + ",openid=" + wxUserID + ",时间为：" + DateTime.Now;
            }
            else
            {
                logContent = "没有获取到微信用户信息,时间为：" + DateTime.Now;
            }
            #region 原有代码
            //string url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
            //GetCode getCode = new GetCode();
            //JObject obj = getCode.GetUrlJObject(url);
            //if (obj != null && obj["openid"] != null)
            //{
            //    wxUserID = obj["openid"].ToString();//微信用户ID存入全局变量
            //    Session["wxUserID"] = obj["openid"].ToString();//微信用户ID存入session会话
            //    logContent = "获取微信返回信息：" + obj.ToString() + ",openid=" + wxUserID + ",时间为：" + DateTime.Now;
            //}
            //else
            //{
            //    logContent = "没有获取到微信用户信息,时间为：" + DateTime.Now;
            //}
            #endregion
            Helper.ExtLog(logContent);
        }
        #endregion

        #region 微信抽奖
        /// <summary>
        /// 微信抽奖
        /// </summary>
        protected ActionResult imgBtuCJ_Click()
        {
            return SelectUser();//微信抽奖
        }
        #endregion

        #region 根据微信ID查询绑定多少用户
        /// <summary>
        /// 根据微信ID查询绑定多少用户
        /// </summary>
        public ActionResult SelectUser()
        {
            if (string.IsNullOrEmpty(wxUserID) || wxUserID == "''")
            {
                //不存在微信，需要登录
                string logContent = "微信ID为空" + ",时间为：" + DateTime.Now;
                Helper.ExtLog(logContent);
                return
                    Json(
                        new
                        {
                            code = (int)BSFAPICode.NormalError,
                            msg = "微信ID为空！",
                            data = new { state = 3 },
                            ReturnUrl = ""
                        });
            }
            //查询微信绑定游戏信息
            string sql = "select * from twx_code where opid = '" + wxUserID + "'";
            DataTable dt = DbSession.Default.FromSql(sql).ToDataTable();

            //绑定了游戏帐号
            if (dt.Rows.Count == 1)
            {
                //根据微信查询绑定的游戏信息
                sql = "select * from tusers where userid =" + dt.Rows[0]["userid"];
                dt = DbSession.Default.FromSql(sql).ToDataTable();

                if (dt != null && dt.Rows.Count >= 1)
                {
                    username = dt.Rows[0]["username"].ToString();
                    userpwd = dt.Rows[0]["pass"].ToString();//数据库中取出的密码是加密过的
                }

                return ReceiveDayGold();//直接抽奖
            }
            else//未绑定游戏帐号
            {
                //需要先登录
                return
                    Json(
                        new
                        {
                            code = (int)BSFAPICode.NormalError,
                            msg = "请先登录！",
                            data = new { state = 4 },
                            ReturnUrl = ""
                        });
            }
        }
        #endregion

        #region 游戏帐号登录抽奖
        /// <summary>
        /// 游戏帐号登录抽奖
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="password"></param>
        public ActionResult imgBtuLogin_Click(string userId, string password)
        {
            if (!string.IsNullOrEmpty(userId) && !string.IsNullOrEmpty(password))
            {
                username = userId;
                string passWord = password;

                if (username.Length < 6 || username.Length > 15)
                {
                    //Helper.JsMsg(this, "游戏名不正确，请重新输入！");
                    return Json(new { code = (int)BSFAPICode.NormalError, msg = "游戏名不正确，请重新输入！", ReturnUrl = "" });
                }
                if (passWord.Length < 6 || passWord.Length > 20)
                {
                    return Json(new { code = (int)BSFAPICode.NormalError, msg = "游戏密码不正确，请重新输入！", ReturnUrl = "" });
                }
                if (Helper.CheckValSql(username) || Helper.CheckValChar(username))
                {
                    return Json(new { code = (int)BSFAPICode.NormalError, msg = "游戏名不正确，请重新输入！", ReturnUrl = "" });
                }

                userpwd = Helper.md5(passWord);
                return ReceiveDayGold(); //开始抽奖
            }
            else
            {
                return Json(new { code = (int)BSFAPICode.NormalError, msg = "请输入账号密码！", ReturnUrl = "" });
            }
        }
        #endregion

        #region 调用存储过程，记录抽奖信息
        /// <summary>
        /// 调用存储过程，记录抽奖信息
        /// </summary>
        public ActionResult ReceiveDayGold()
        {
            try
            {
                if (wxUserID == "" && Session["wxUserID"] != null)
                {
                    wxUserID = Session["wxUserID"].ToString();
                }

                Dictionary<string, object> dic = new Dictionary<string, object>();
                object result = Bzw.Data.DbSession.Default.FromProc("Web_pUserWxFocusGame")
                      .AddInputParameter("@WxID", DbType.String, wxUserID)
                      .AddInputParameter("@UserName", DbType.String, username)
                      .AddInputParameter("@MD5Password_arg", DbType.String, userpwd)
                      .AddReturnValueParameter("@Return_Value", DbType.Int32)
                      .ToScalar(out dic);

                Helper.ExtLog("传入存储过程参数：微信ID=" + wxUserID + ";username=" + username + ";pwd=" + userpwd);
                string returnStr = string.Empty;
                if (dic.Count > 0)
                {
                    mony = result == null ? "" : result.ToString();

                    string returnValue = dic["Return_Value"].ToString();
                    if (!string.IsNullOrEmpty(returnValue))
                    {
                        //成功
                        if (returnValue == "0")
                        {
                            //领取失败
                            return
                                Json(
                                    new
                                    {
                                        code = (int)BSFAPICode.Success,
                                        msg = "成功！",
                                        data = new { state = 2 },
                                        ReturnUrl = ""
                                    });
                        }
                        else if (returnValue == "1" || returnValue == "2")
                        {
                            //领取失败
                            return
                                Json(
                                    new
                                    {
                                        code = (int)BSFAPICode.NormalError,
                                        msg = "帐号或密码错误！",
                                        data = new { state = 4 },
                                        ReturnUrl = ""
                                    });
                        }
                        else if (returnValue == "3")
                        {
                            //领取失败
                            return
                                Json(
                                    new
                                    {
                                        code = (int)BSFAPICode.NormalError,
                                        msg = "每个账号只能领取一次！",
                                        data = new { state = 1 },
                                        ReturnUrl = ""
                                    });
                        }
                    }
                }
                if (!string.IsNullOrEmpty(returnStr))
                {
                    string logContent = "抽奖鱼币数据库返回：" + returnStr + ",时间为：" + DateTime.Now;
                    Helper.ExtLog(logContent);
                    //领取失败
                    return
                        Json(
                            new
                            {
                                code = (int)BSFAPICode.NormalError,
                                msg = "网络异常！",
                                data = new { state = 0 },
                                ReturnUrl = ""
                            });
                }
                //领取失败
                return
                    Json(
                        new
                        {
                            code = (int)BSFAPICode.NormalError,
                            msg = "网络开小差！",
                            data = new { state = 0 },
                            ReturnUrl = ""
                        });
            }
            catch (Exception ex)
            {
                string logContent = "抽奖调用存储过程，出现异常：" + ex.Message + ",时间为：" + DateTime.Now;
                Helper.ExtLog(logContent);
                //领取失败
                return
                    Json(
                        new
                        {
                            code = (int)BSFAPICode.NormalError,
                            msg = "领取异常！",
                            data = new { state = 1 },
                            ReturnUrl = ""
                        });
            }
        }
        #endregion

        #region 选择游戏
        /// <summary>
        /// 选择游戏
        /// </summary>
        protected ActionResult ImgBtuChooseGame(string uName)
        {
            username = uName;
            return ReceiveDayGold();
        }
        #endregion
    }
}